package org.jeecg.modules.simulator.rooter;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.simulator.Simulator;

import org.jeecg.modules.simulator.factory.train.plan.TrainActionRDSFactory;
import org.jeecg.modules.simulator.model.MetroTrain;
import org.jeecg.modules.simulator.model.SceneDataType;
import org.jeecg.modules.simulator.model.orbit.OrbitPath;
import org.jeecg.modules.simulator.model.orbit.OrbitPoint;
import org.jeecg.modules.simulator.model.train.TrainBiz;
import org.jeecg.modules.simulator.model.train.action.TrainActionRecorder;

import org.jeecg.modules.simulator.model.train.event.TrainRecordEvent;
import org.jeecg.modules.simulator.model.train.event.TrainUpEvent;
import org.jeecg.modules.simulator.model.line.plan.TrainPlanTablePath;
import org.jeecg.modules.simulator.model.train.TrainRunState;
import org.jeecg.modules.simulator.model.train.action.ActionRecordersStatus;
import org.jeecg.modules.simulator.model.train.action.ExecutionStatus;
import org.jeecg.modules.simulator.model.train.action.TrainActionRecorders;
import org.jeecg.modules.simulator.model.train.manager.PlanTableManager;
import org.jeecg.modules.simulator.model.train.manager.TrainActionRdsManager;
import org.jeecg.modules.simulator.model.train.manager.TrainCalculateBizManager;
import org.jeecg.modules.simulator.model.train.manager.trainmanager.EndState;
import org.jeecg.modules.simulator.model.train.manager.trainmanager.StartState;
import org.jeecg.modules.simulator.model.train.manager.trainmanager.SucceedState;
import org.jeecg.modules.simulator.model.train.manager.trainmanager.TrainState;
import org.jeecg.modules.simulator.model.train.timeplan.TrainPlanTable;

import org.jeecg.modules.simulator.recorder.TrainManagerAllDayIniter;
import org.jeecg.modules.simulator.recorder.TrainManagerPeriodTimeIniter;
import org.jeecg.modules.simulator.recorder.TrainRecorder;
import org.jeecg.modules.simulator.util.SpringUtil;
import org.jeecg.modules.simulator.util.TimeUtil;
import lombok.Getter;
import org.jeecg.modules.simulator.util.UnitCache;
import org.jeecg.modules.simulator.vo.TrainDyInfo;
import org.jeecg.modules.simulator.vo.TrainPosition;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.ApplicationContext;

import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program:
 * @description: 业务动作：上线
 * 1、检查时刻表是否到了发车时间点，到了发车时间点，把动作记录表设置为开始，同时发出发车消息pathitem
 * 2、场段给TrainManager发车消息，TrainManager接收到消息，获取待上线的车辆对象----这个地方需要问一下
 * 3、把待上线车辆对象加入到trainmanagerd管理map。
 * 2
 * 业务动作：初始化
 * 1、车辆记录表初始化，把车辆的时刻表转换成车辆动作记录表
 * 业务动作：车辆运行
 * 1、检查车辆运行状态，根据列车时刻表发动作给车辆
 * 业务动作：车辆下线
 * 1、车辆到站，检查车辆要下线，如果要下线，从管理车辆队列中移除，同时去除车辆对象
 * 2、把车辆对象传递给下线场段，
 * <p>
 * 3、下线场段接收车辆对象，放入到待发车队列中
 * @author: renzhg
 * @create: 2024-08-08 10:01
 **/
@Slf4j
public class TrainManager implements Simulator {
    private static final Logger logger = LoggerFactory.getLogger(TrainManager.class);

    @Setter
    @Getter
    String lineId;
    @Setter
    private LocalTime startTime;


    @Setter
    @Getter
    OrbitPath upOrbitPath;//上行轨道
    @Setter
    @Getter
    OrbitPath downOrbitPath;//下行轨道


    PlanTableManager planTableManager = new PlanTableManager();


    Map<String, OrbitPoint> workUpOrbitPointMap = new HashMap<>();


    Map<String, OrbitPoint> workDownOrbitPointMap = new HashMap<>();


    @Setter
    @Getter
    String trainType;
    @Getter
    List<String> finishedTrainList = new ArrayList<>();




    //有历史数据加载的时候使用
    public void setWorkOrbitPath() {

        upOrbitPath.forEach(orbitPoint -> {
            workUpOrbitPointMap.put(orbitPoint.getOrbitName(), orbitPoint);
        });

        downOrbitPath.forEach(orbitPoint -> {
            workDownOrbitPointMap.put(orbitPoint.getOrbitName(), orbitPoint);
        });
    }


    /**
     * @description: 计算业务管理者
     * @author: renzhg
     * @date: 2024/8/6 14:44
     **/

    //trainId+"-"+trainNum
    @Getter
    Map<String, List<TrainPlanTable>> trainPlanTableMap = new HashMap<>();
    @Getter
    TrainCalculateBizManager trainCalculateBizManager = new TrainCalculateBizManager();
    //时间片段装配厂
    @Getter
    TrainManagerPeriodTimeIniter trainManagerPeriodTimeIniter = new TrainManagerPeriodTimeIniter();
    //历史全天数据装配厂
    TrainManagerAllDayIniter trainManagerAllDayIniter = new TrainManagerAllDayIniter();
    /**
     * @description:
     * @author: renzhg
     * @date: 2024/8/6 14:45
     **/
    @Getter
    TrainActionRdsManager trainActionRdsManager = new TrainActionRdsManager();

//列车状态统计
    @Getter
    TrainStateStatisticser trainStateStatisticser = new TrainStateStatisticser();
    /**
     * @description: 车辆信息，key是列车id-列车车次号，value是列车对象，列车对象包括列车的物理信息，列车的时刻表信息
     * @author: renzhg
     * @date: 2024/7/25 15:50
     **/
//    private ConcurrentHashMap<String, MetroTrain> trainMap = new ConcurrentHashMap<>();

//在线列车
    @Getter
    private Map<String, MetroTrain> trainMap = new HashMap<>();

    public String getEarliestStartTime() {
        List<String> timeList = new ArrayList<>();
        for (Map.Entry<String, List<TrainPlanTable>> tptEntry : trainPlanTableMap.entrySet()) {
            List<TrainPlanTable> trainPlanTables = tptEntry.getValue();
            Collections.sort(trainPlanTables); // 对列表进行排序
            String arriveTime = trainPlanTables.get(0).getArriveTime();
            timeList.add(arriveTime);
        }

        timeList.sort(Comparator.comparing(LocalTime::parse));
        return timeList.get(0);


    }
    //查询当前列车行驶位置
//    public TrainPosition getCurrentTrainPosition(String trainIdNum, LocalTime time) {
//        MetroTrain metroTrain = trainMap.get(trainIdNum);
//        return metroTrain.getCurrentTrainPosition(time);
//    }

    //查询所有列车行驶位置
    public Map<String, TrainPosition> getAllTrainPosition(String time) {
        Map<String, TrainPosition> trainPositionMap = new HashMap<>();
        for (Map.Entry<String, MetroTrain> entry : trainMap.entrySet()) {

            String trainId = entry.getValue().getTrainId();
            String lineId = entry.getValue().getBelongLineId();
            String trainNum = entry.getValue().getTrainNum();
//            if(entry.getValue().getPersonMap().size()>0){
//                System.out.println("fdsafasfasdfas");
//            }

//            if (entry.getKey().equals("lsAdd01-01")) {
//                logger.debug("lsAdd01-01");
//            }
//            System.out.println("getAllTrainPosition----当前列车编号：" + trainId + "_" + trainNum);
            String itemName=entry.getValue().getCurrentTrainActionRecorder().getTableItemName();
            String itid=entry.getValue().getCurrentTrainActionRecorder().getTableItemId();
            TrainPosition trainPosition = entry.getValue().getCurrentTrainPosition(trainId,
                    lineId,
                    trainNum, time,itemName,itid);
            if (trainPosition != null) {
                trainPositionMap.put(entry.getKey(), trainPosition);
            }

        }


        return trainPositionMap;
    }


//    public void assignTrainManager(LocalTime startTime, SceneDataType sceneDataType) {
//
//        try {
//            if (!sceneDataType.equals(SceneDataType.timePeriodHistoryData)) {
////                列车时刻表装配
//
//            } else {
//
//
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }






//    列车时刻表转换成列车动作记录表
    public void  initAllDayAssign() {
        trainManagerAllDayIniter.init(lineId);

        Map<String, TrainPlanTablePath> trainPlanTablePathMap = trainCalculateBizManager.getTrainPlanTablePathMap();
        trainPlanTablePathMap.entrySet().removeIf(entry -> entry.getValue().size() < 2);
        Map<String, TrainActionRecorders> stringTrainActionRecordersMap = trainManagerAllDayIniter.allDayTimeParkTrainActionRDsMap(trainPlanTablePathMap);
        trainActionRdsManager.setTrainActionRecordersMap(stringTrainActionRecordersMap);
//        trainActionRdsManager

    }


    public void initPeriodTimeAssign(){
        trainManagerPeriodTimeIniter.init(lineId, workUpOrbitPointMap, workDownOrbitPointMap, upOrbitPath, downOrbitPath);
        try {
        Map<String, TrainPlanTablePath> trainPlanTablePathMap = trainCalculateBizManager.getTrainPlanTablePathMap();
        trainPlanTablePathMap.entrySet().removeIf(entry -> entry.getValue().size() < 2);
        //列车时刻表装配
        //列车时刻表转化为列车动作路径
        //把列车摆放到响应的位置，如果是直接场段开始的就放在场段，如果是线网，则放在线网上
        //同时把相应的列车动作表调整到对应位置上
        Map<String, TrainActionRecorders> stringTrainActionRecordersMap = trainManagerPeriodTimeIniter.timePeriodAssignTrain(startTime, trainPlanTablePathMap);
        trainActionRdsManager.setTrainActionRecordersMap(stringTrainActionRecordersMap);
        this.trainMap = trainManagerPeriodTimeIniter.caculateInNetTimePeriodTrainActionRecorders(trainPlanTablePathMap, startTime, trainType);
             } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void addSimplePlanTable(TrainPlanTable firstTrainPlanTable, long planSpeed, String now) {
        planTableManager.createSimplePlanTable(firstTrainPlanTable, planSpeed, now);
    }


    /**
     * @description: 线路对应有多少列车，key是线路上下行，value是列车id-列车车次号
     * @author: renzhg
     * @date: 2024/8/6 11:00
     **/
    private Map<String, List<String>> lineMap;


    //region  文件数据读取代码


    /**
     * @description: 初始化车辆信息，从文件中读取车辆信息，初始化车辆信息，车辆信息包括车辆的物理信息，车辆的时刻表信息
     * @author: renzhg
     * @date: 2024/8/6 10:40
     **/
    public void initTrainMap(Map<String, List<TrainPlanTable>> TrainPlanTableMap) {
        //装配路径
        trainPlanTableMap = TrainPlanTableMap;
        initTrainPlanTablePathMap(TrainPlanTableMap);

    }

    /**
     * @description: 1、初始化列车时刻表，从每个时刻表中拿出第一个时刻表，按时间排序，生成一个时间点对应的列车时刻表map
     * 2、初始化列车时刻表路径，生成一个列车时刻表路径map，key是列车id-列车车次号，value是列车时刻表路径对象
     * @author: renzhg
     * @date: 2024/9/5 17:57
     **/
    public void initTrainPlanTablePathMap(Map<String, List<TrainPlanTable>> TrainPlanTableMap) {
        this.trainPlanTableMap = TrainPlanTableMap;
        Map<String, TrainPlanTablePath> trainPlanTablePathMap = new HashMap<>();
        List<TrainPlanTablePath> trainPlanTablePaths = new ArrayList<>();
        for (Map.Entry<String, List<TrainPlanTable>> entry : TrainPlanTableMap.entrySet()) {
            List<TrainPlanTable> trainPlanTables = entry.getValue();
            TrainPlanTablePath trainPlanTablesPath = new TrainPlanTablePath(this.lineId,trainPlanTables, entry.getKey());

            trainPlanTablePathMap.put(entry.getKey(), trainPlanTablesPath);
            trainPlanTablePaths.add(trainPlanTablesPath);


        }
// trainPlanTablesPath.getFirstTime();

        Map<String, List<TrainPlanTablePath>> trainPlanTablePathTimeMap =
                trainPlanTablePaths.stream()
                        .sorted(Comparator.comparing(TrainPlanTablePath::getFirstTime))
                        .collect(Collectors.groupingBy(TrainPlanTablePath::getFirstTime));

        Map<String, List<TrainPlanTablePath>> lstrainPlanTablePathTimeMap = new LinkedHashMap<>(trainPlanTablePathTimeMap);
//        trainCalculateBizManager.getStationPiontTimeNoTrain(trainPlanTablePathMap);
        trainCalculateBizManager.setStartTrainTimeMap(lstrainPlanTablePathTimeMap);
        trainCalculateBizManager.setTrainPlanTablePathMap(trainPlanTablePathMap);
    }

    //end region

    /**
     * @description: 业务场景一：场段完成发车准备后给消息TrainManager,TrainManager将车添加到自己的管理队列中
     * @author: renzhg
     * @date: 2024/9/3 13:08
     **/
//    @EventListener
    public void addTrain2trainMap(MetroTrain train) {
        trainMap.put(train.getTrainId() + "-" + train.getTrainNum(), train);
    }


    /**
     * @description: 业务场景下线：车辆到站，检查车辆要下线，如果要下线，从管理车辆队列中移除，同时去除车辆对象
     * @author: renzhg
     * @date: 2024/9/3 13:15
     **/
    public void downLoadNet(MetroTrain train) {
        finishedTrainList.add(train.getTrainId() + "-" + train.getTrainNum());
//        trainMap.remove(train.getTrainId() + "-" + train.getTrainNum());
    }


    public void inssertTrainActionRDsMap(String key, TrainActionRecorders trainActionRecorders) {
        trainActionRdsManager.getTrainActionRecordersMap().put(key, trainActionRecorders);
    }


//region  旧代码
//    /**
//     * @description: 初始化网络的时候，把列车时刻表匹配到网络中的列车上，这里列车的位置也根据时刻表来设置
//     * @author: renzhg
//     * @date: 2024/10/2 15:41
//     **/
//    public void caculateInNetTrainActionRecorders(Map<String, TrainPlanTablePath> trainPlanTablePathMap, LocalTime timePoint) {
//        Map<String, TrainActionRecorders> trainActionRecorders = createTrainActionRecorders(trainPlanTablePathMap);
//        int i = 0;
//        trainPlanTablePathMap.forEach((k, v) -> {
//            //取出要装配的列车
//            MetroTrain metroTrain = new MetroTrain();
//            metroTrain.setTrainPhysics(UnitCache.globalSceneBaseData.getTrainPhysicsMap().get(trainType));
//            TrainActionRecorders trainActionRecoders = trainActionRecorders.get(k);
//            metroTrain.setTrainId(trainActionRecoders.getRocordersId().split("-")[0]);
//            metroTrain.setTrainNum(trainActionRecoders.getRocordersId().split("-")[1]);
//            if (metroTrain.getTrainId().equals("104") && metroTrain.getTrainNum().equals("03")) {
//                logger.debug("104-01");
//            }
//            metroTrain.setBelongLineId(this.lineId);
//            String firstName = trainActionRecoders.getFristTrainActionRecorder().getName();
//            TrainBiz trainBiz = new TrainBiz(workDownOrbitPointMap);
//            metroTrain.setTrainBiz(trainBiz);
//
//            if (this.upOrbitPath.getFirstPointName().equals(firstName)) {
//                metroTrain.setIsRuningUp(true);//设立上行方向
//
//            } else if (this.downOrbitPath.getFirstPointName().equals(firstName)) {
//                metroTrain.setIsRuningUp(false);//设立下行方向
//
//            }
//
//            while (trainActionRecoders.moveNext()) {
//                TrainActionRecorder currentTrainActionRecorder = trainActionRecoders.getCurrentTrainActionRecorder();
//                int compareStartTime = TimeUtil.compareLocalTimes(currentTrainActionRecorder.getStartTime(), timePoint);
//                int compareEndTime = TimeUtil.compareLocalTimes(currentTrainActionRecorder.getEndTime(), timePoint);
//                if (compareEndTime == 1) {//如果结束时间在当前时间之前，设置动作记录为结束
//                    currentTrainActionRecorder.setFinished(true);
//                } else if (compareStartTime == 1 && compareEndTime == 0) {
//                    metroTrain.setOneTimePtInitTrainStatue(currentTrainActionRecorder, timePoint);
//                    break;
//                }
//                trainMap.put(metroTrain.getTrainId() + "-" + metroTrain.getTrainNum(), metroTrain);
//
//            }
//
//
//        });
//
//
//    }

    //end region

    public List<TrainPlanTablePath> dispatchFistBatchTrain() {
        if (!trainCalculateBizManager.getStartTrainTimeMap().isEmpty()) {
            Map.Entry<String, List<TrainPlanTablePath>> firstEntry = trainCalculateBizManager.getStartTrainTimeMap().entrySet().iterator().next();
            return firstEntry.getValue();

        }

        return null;

    }


    /**
     * 功能描述：检查车辆运行状态，监听异常事件，给相关车辆发命令
     *
     * @author renowen2005
     * @date: 2024/07/24 17:28
     */
    void caculateCheckMetroTrainState() {
        for (String key : trainMap.keySet()) {
            MetroTrain train = trainMap.get(key);
            if (train.getTrainRunState() == TrainRunState.stop) {
                disposeExecpetion();
            }

        }

    }


    /**
     * @description: 时刻表数据检查
     * 1、是否是开始执行时间，到了则把动作记录表设置为开始
     * @author: renzhg
     * @date: 2024/7/25 14:43
     **/
    List<TrainActionRecorders> checkTrainTimetable(String time) {
        final int PREVIOUS_SECONDS = 2;

        LocalTime localTime = LocalTime.parse(time);
        List<TrainActionRecorders> trainActionRecordersList = new ArrayList<>();

//        if (TARGET_TIME.equals(time)) {
//            System.out.println("checkTrainTimetable");
//        }

        try {
            Map<String, TrainActionRecorders> trainActionRecordersMap = trainActionRdsManager.getTrainActionRecordersMap();
            trainActionRecordersList = trainActionRecordersMap.values().stream()
                    .filter(trainActionRecorder -> isMatchingTime(localTime, trainActionRecorder, PREVIOUS_SECONDS))
                    .peek(trainActionRecorder -> trainActionRecorder.setStatus(ActionRecordersStatus.start))
                    .collect(Collectors.toList());

        } catch (Exception e) {
            System.err.println("Error while checking train timetable: " + e.getMessage());
            e.printStackTrace();
        }

        return trainActionRecordersList;
//        if (time.equals("06:35:31")) {
//            System.out.println("checkTrainTimetable");
//        }
//String testLineId=this.lineId;
//        LocalTime localTime = LocalTime.parse(time);
//        List<TrainActionRecorders> trainActionRecorderslist = new ArrayList<>();
//        try {
//            Map<String, TrainActionRecorders> trainActionRecordersMap = trainActionRdsManager.getTrainActionRecordersMap();
//            for (String key : trainActionRecordersMap.keySet()) {
////                if (trainActionRecordersMap.get(key).getLastTrainActionRecorder().isFinished()) {
////                    finishedTrainList.add(key);
////                }
////                if (getLineId().equals("10") && key.equals("112-02")) {
////                    System.out.println("112-02-10");
////                }
//                //提前了两秒发布消息
//                LocalTime firstActionTime = trainActionRecordersMap.get(key).getFistActionTime();
//                LocalTime clonedTime = firstActionTime.withNano(firstActionTime.getNano());
////                if (getLineId().equals("10") && key.equals("103-01") && time.equals("06:17:23")) {
////                    System.out.println("103-01-10");
////                }
//                LocalTime updatedTime = clonedTime.minusSeconds(2);
//                TrainActionRecorders trainActionRecorders = trainActionRecordersMap.get(key);
//                if (TimeUtil.compareLocalTimes(localTime, updatedTime) == 0) {
//
//                    trainActionRecorders.setStatus(ActionRecordersStatus.start);
//                    trainActionRecorderslist.add(trainActionRecorders);
////                    trainActionRecordersMap.put(key,trainActionRecorders);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//
//        }
////        System.out.println("检查是否有开始运行的车辆");
//
//        return trainActionRecorderslist;
    }

    private boolean isMatchingTime(LocalTime localTime, TrainActionRecorders trainActionRecorder, int previousSeconds) {
        LocalTime firstActionTime = trainActionRecorder.getFistActionTime();
        LocalTime updatedTime = firstActionTime.minusSeconds(previousSeconds);
        return TimeUtil.compareLocalTimes(localTime, updatedTime) == 0;
    }
    @Override
    public LocalTime getCurrentTime() {
        return this.currentTime;
    }

    @Override
    public void UpdateCurrentTime(LocalTime currentTime) {
        this.currentTime = currentTime;
    }

    LocalTime currentTime;

    @Override
    public void nextTime(String now, Integer step) {
        List<TrainActionRecorders> trainActionRecordersList = checkTrainTimetable(now);
        if (!trainActionRecordersList.isEmpty()) {
            SpringUtil.getApplicationContext().publishEvent(new TrainUpEvent(trainActionRecordersList));
        }

        updateAndBroadcastTrainStatus(now);
    }

    /**
     * @description: 派发时刻表动作记录，交到列车执行
     * @author: renzhg
     * @date: 2024/7/29 16:06
     **/
    public void dispatchTimeTableActionRecorders(String trainkey, MetroTrain metroTrain, String now) {
        Map<String, TrainActionRecorders> trainActionRecordersMap = trainActionRdsManager.getTrainActionRecordersMap();
        // 假设trainActionRecordersMap和trainMap已经是线程安全的，或者在访问时已经做了适当的同步处理
        TrainActionRecorders trainActionRecorders = trainActionRecordersMap.get(trainkey);
        metroTrain.processTrainAction(trainActionRecorders.getCurrentTrainActionRecorder(), now);
    }


    /**
     * @description: 这里应该是列车动作执行完后的消息，发送，
     * 人流应该从这个消息队列接受到车到站的消息
     * @author: renzhg
     * @date: 2024/7/29 16:23
     **/
    public void broadcastMessage(ApplicationContext context, MetroTrain train) {

        //临时注释掉，等代码完全时候，再打开
//        context.publishEvent(new TrainUpDateEvent(train));
    }

    /**
     * @description: 更新状态
     * @author: renzhg
     * @date: 2024/7/29 16:18
     **/

    void updateAndBroadcastTrainStatus(String now) {
//        logger.debug("列车数量:" + trainMap.size());
//        System.out.println("updateAndBroadcastTrainStatus:列车更新状态代码");
//        if (now.equals("08:00:57")) {
//            logger.debug("08:00:30");
//        }
        String testLineId=this.lineId;
        LocalTime localTime = LocalTime.parse(now);
        Map<String, TrainActionRecorders> trainActionRecordersMap = trainActionRdsManager.getTrainActionRecordersMap();
        try {
            trainMap.forEach((key, train) -> {
//                System.out.println("列车id:" + train.getTrainId());
//                System.out.println("列车num:" + train.getTrainNum());


                if (train.getTrainId().equals("112") && train.getTrainNum().equals("02") && train.getBelongLineId().equals("10")) {
                    logger.debug("10_112_02");
                }
                if (trainActionRecordersMap.get(key).getLineId().equals(this.lineId)) {

                    TrainState state = null;
                    if (trainActionRecordersMap.get(key).getStatus().equals(ActionRecordersStatus.start)) {
                        state = new StartState();
                        state.handle(this, key, train, now);
                    } else if (trainActionRecordersMap.get(key).getStatus().equals(ActionRecordersStatus.end)) {
                        state = new EndState();
                        state.handle(this, key, train, now);
                    } else if (train.getCurrentExecutionStatus() == ExecutionStatus.succeed) {
                        state = new SucceedState();
                        state.handle(this, key, train, now);
                    }
                    TrainActionRecorders trainActionRecorders = trainActionRecordersMap.get(key);


                    train.update(now, trainActionRecorders);
                    try {
                        broadcastMessage(SpringUtil.getApplicationContext(), train);
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.err.println("Error broadcasting message for train " + train.getTrainId() + ": " + e.getMessage());
                    }
                }
            });


            finishedTrainList.forEach(key -> {
                if(trainMap.containsKey(key)){
                    trainMap.remove(key);
                }

            });
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Unexpected error during train status update: " + e.getMessage());
        }
    }

    //region 旧代码
//    void updateAndBroadcastTrainStatus(LocalTime now) {
//        System.out.println("列车数量:" + trainMap.size());
//        System.out.println("updateAndBroadcastTrainStatus:列车更新状态代码");
//        Map<String, TrainActionRecorders> trainActionRecordersMap = trainActionRdsManager.getTrainActionRecordersMap();
//        try {
//            trainMap.forEach((key, train) -> {
//                System.out.println("列车id:" + train.getTrainId());
//                train.update(now);
//                // 对于广播消息和状态更新操作，考虑捕获并处理可能的异常
//                try {
//                    broadcastMessage(SpringUtil.getApplicationContext(), train);
//                } catch (Exception e) {
//                    // 记录或处理异常，确保程序健壮性
//                    System.err.println("Error broadcasting message for train " + train.getTrainId() + ": " + e.getMessage());
//                }
//                //动作开始
//                if (trainActionRecordersMap.get(key).getStatus().equals(ActionRecordersStatus.start)) {
//                    System.out.println("列车id:" + train.getTrainId() + "开始运行");
//                    try {
//                        dispatchTimeTableActionRecorders(key, train, now);
//                        trainActionRecordersMap.get(key).setStatus(ActionRecordersStatus.starting);
//                    } catch (Exception e) {
//                        // 对于调度操作的异常也进行捕获和处理
//                        System.err.println("Error dispatching timetable action recorders for train " + train.getTrainId() + ": " + e.getMessage());
//                    }
//                    //动作成功
//                } else if (trainActionRecordersMap.get(key).getStatus().equals(ActionRecordersStatus.end)) {
//                    Optional<TrainActionRecorder> result = trainActionRecordersMap.get(key).getTrainActionRecordMap().values().stream()
//                            .filter(TrainActionRecorder::isLast)
//                            .findFirst();
//                    if(result.isPresent()) {
//                        String stationname=result.get().getName();
//                        Train2LastStationMsg train2LastStationMsg = new Train2LastStationMsg();
//                        downLoadNet(train);
//                        train2LastStationMsg.setTrain(train);
//                        train2LastStationMsg.setStopStationName(stationname);
//                        train2LastStationMsg.setTime(now);
//                        SpringUtil.getApplicationContext().publishEvent(new TrainDownLoadEvent(train2LastStationMsg));
//                    }
//                }
//                if (train.getCurrentExecutionStatus() == ExecutionStatus.succeed) {
//                    try {
//                        TrainActionRecorders trainActionRecorders = trainActionRecordersMap.get(key);
//                        trainActionRecorders.moveNext();
//                        dispatchTimeTableActionRecorders(key, train, now);
//                    } catch (Exception e) {
//                        // 对于调度操作的异常也进行捕获和处理
//                        System.err.println("Error dispatching timetable action recorders for train " + train.getTrainId() + ": " + e.getMessage());
//                    }
//                }
//            });
//        } catch (Exception e) {
//            // 捕获并处理可能的异常，确保整个方法的健壮性
//            System.err.println("Unexpected error during train status update: " + e.getMessage());
//        }
//
//    }
    //endregion


    /**
     * 功能描述：处理停车异常动作
     *
     * @author renowen2005
     * @date 2024/07/24 17:24
     */
    private void disposeExecpetion() {

    }


//    @Override
//    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//        this.context = applicationContext;
//    }


//    @Override
//    public Date getCurrentTime() {
//        return null;
//    }
//
//    @Override
//    public void nextTime(LocalTime  now) {
//        //时刻表检查
//
//    }
}
